package models.helpers;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class DBSession {
    private static SqlSessionFactory factory;

    public static SqlSession openSession() throws IOException {
        SqlSessionFactory sessionFactory = DBSession.getFactory();
        return sessionFactory.openSession();
    }

    private static SqlSessionFactory getFactory() throws IOException {
        if (factory == null) {
            String resource = "mybatis/conf/ibatis.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            factory = new SqlSessionFactoryBuilder().build(reader);
        }
        return factory;
    }
}
